import { Component, OnInit } from '@angular/core';
import { JsonApiService } from "app/core/api/json-api.service"; //http请求配置引入
import {config} from '../../shared/smartadmin.config';

declare var $: any;
@Component({
	selector: 'sa-api',
	templateUrl: './api.component.html',
})
export class ApiComponent implements OnInit {
	tableData:any[] = []; //table数据
	resultTableData:any[] = [] //客户端分页数据暂存
	totalCount:number = 0; //分页总条数
	curPage:number = 1; //分页当前页
	pageSize:number = 10; //内置的分页每页条数
	searchKey:string = ''; //搜索keyword
	userNameList:any[] = []; //用户数据集合
	userName:string = ''; //用户名
	apiNameList:any[] = []; //api数据集合
	apiName:string = ''; //api
	startTime:string = '';//开始时间
	endTime:string = '';	//结束时间
	userFlag:boolean = false;
	timeType:string = '0';
	isShow:boolean;
	constructor(private jsonApiService: JsonApiService) {}
	//刷新
	refresh(){
		this.load();
	}
	ngOnInit() {
		System.import('assets/js/datepicker/js/bootstrap-datetimepicker.min.js').then(()=>{
			System.import('assets/js/datepicker/locales/bootstrap-datetimepicker.zh-CN.js').then(()=>{
				this.initDate().then(()=>this.load());//初始化日期,加载table表格数据
			})
		})
		System.import('script-loader!select2/dist/js/select2.min.js').then(()=>{
			System.import('assets/js/select2-zh-CN.js').then(()=>{
				this.selectUserName();//初始化用户 
				this.selectApiName();//初始化api
				this.queryUserName().then(()=>{this.selectUserName();});
				this.queryApiName().then(()=>{this.selectApiName();});
			})
		})
	}
	getTime(Date,type){
		var year = Date.getFullYear();
		var month = (Date.getMonth() + 1) < 10 ? "0" + (Date.getMonth() + 1) : (Date.getMonth() + 1);
		var day = Date.getDate()  < 10 ? "0" + Date.getDate() : Date.getDate();
		var hour = Date.getHours() < 10 ? "0" + Date.getHours() : Date.getHours();
		var minute = Date.getMinutes() < 10 ? "0" + Date.getMinutes() : Date.getMinutes();
		var second = Date.getSeconds() < 10 ? "0" + Date.getSeconds() : Date.getSeconds();
		if(type === '1'){
			return year+"-"+month+"-"+day+" "+hour+":"+minute+":"+second;
		}else if(type === '2'){
			return year+"-"+month+"-"+day;
		}
	}
	//时间类型的变化
	timeTypeChange(e){
		this.timeType = e;
		$('#datetimepicker1').datetimepicker('remove');
		$('#datetimepicker2').datetimepicker('remove');
		this.initDate();
	}
	//初始化日期
	initDate(){
		var that = this;
		return new Promise(function (resolve, reject) {
			if(that.timeType === '0'){
				var formatType = 'yyyy-mm-dd hh:ii:ss';
				var viewNumber = 0;
				var type = '1';
			}else if(that.timeType === '1'){
				var formatType = 'yyyy-mm-dd'
				var viewNumber = 2;
				var type = '2';
			}
			$("#datetimepicker1").datetimepicker({//时间插件
					format: formatType,
				    language: "zh-CN",
				    autoclose: true,
				    minView:viewNumber
				}).on("changeDate", function(e){
					var date = e.date;
					if(!date){return;};
					var time = that.getTime(date,type);
					$("#datetimepicker2").datetimepicker("setStartDate", time);
				});
				$("#datetimepicker2").datetimepicker({//时间插件
					format: formatType,
				    language: "zh-CN",
				    autoclose: true,
				    minView:viewNumber
				}).on("changeDate", function(e){
					var date = e.date;
					if(!date){return;}
					var time = that.getTime(date,type);
					$("#datetimepicker1").datetimepicker("setEndDate", time);
				});
				var date = new Date();
				$("#datetimepicker2").val(that.getTime(date,type));//当前时间
				date.setDate(date.getDate() - 7);//设置前一周
				$("#datetimepicker1").val(that.getTime(date,type));
			resolve();
		})
	}
	//擦除api所选值
	delApiName(){	
		this.apiName = '';
		//采用简单粗暴的方法清除;官方推荐的方法失效
		var str=$("<span class='select2-selection__placeholder'>请选择</span>");
		$('#apiNameSelect2').val("");
		$("#select2-apiNameSelect2-container").empty();
		$("#select2-apiNameSelect2-container").attr("title","");
		$("#select2-apiNameSelect2-container").prepend(str);
	}
	//拉取api数据
	queryApiName(){
		var that = this;
		return new Promise(function (resolve, reject) {
			that.jsonApiService.http("apistatistics/queryapiNameList.html", null).subscribe(data => {
				if(data.success){
					var apilist = data.data;
		        	var selectdata = [];
		        	for(var i = 0 ; i < apilist.length ; i++) {
		        		var obj = {
		        			id:i,
		        			text:apilist[i],
		        		}
		        		selectdata[i] = obj;
		        	}
		        	that.apiNameList = selectdata;
		        	resolve();
				}else{
					reject();
				}
			})
		})
	}
	//初始化api Select2选项
	selectApiName(){
		var that = this;
		$("#apiNameSelect2").select2({
	    	language : "zh-CN",
	    	placeholder :"请选择",
	    	allowClear : true,
	    	data : this.apiNameList,//为Select添加数据
	        templateResult: this.formatRepo2
	    }).on ("select2:select", function (e){
        	  var data = e.params.data;
        	  that.apiName = data.text;
       });
	}
	//擦除用户所选值
	delUserName(){
		this.userName = '';
		//采用简单粗暴的方法清除;官方推荐的方法失效
		var str=$("<span class='select2-selection__placeholder'>请选择</span>");
		$('#userNameSelect2').val("");
		$("#select2-userNameSelect2-container").empty();
		$("#select2-userNameSelect2-container").attr("title","");
		$("#select2-userNameSelect2-container").prepend(str);
	}
	//拉取用户数据
	queryUserName(){
		var that = this;
		return new Promise(function (resolve, reject) {
			that.jsonApiService.http("apistatistics/queryuserNameList.html", null).subscribe(data => {
				if(data.success){
					var userlist = data.data;
		        	var selectdata = [];
		        	for(let item in userlist) {
		        		var obj = {
		        			id:item,
		        			text:userlist[item],
		        		}
		        		selectdata.push(obj);
		        	}
		        	that.userNameList = selectdata;
		        	resolve();
				}else{
					reject();
				}
			})
		})
	}
	//初始化select2 车辆选项
	selectUserName(){
		var that = this;
		$("#userNameSelect2").select2({
	    	language : "zh-CN",
	    	placeholder :"请选择",
	    	allowClear : true,
	    	data : this.userNameList,//为Select添加数据
	        templateResult: this.formatRepo
	    }).on("select2:select", function (e){
        	  	var data = e.params.data;
        	  	that.userName = data.id;
        });

	}
	//select2 格式回调函数
	formatRepo (state) {
		if (!state.id) {return state.text};
		var $state = $('<span><i class="fa fa-user green"></i>&nbsp;&nbsp;' + state.text + '</span>');
		return $state;
	}
	//select2 格式回调函数
	formatRepo2 (state) {
		if (!state.id) {return state.text};
		var $state = $('<span><i class="fa fa-paperclip green"></i>&nbsp;&nbsp;' + state.text + '</span>');
		return $state;
	}
	//查询
	search_data(){
		this.curPage = 1;
		this.load();
	}
	//加载list数据
	load() {
		this.startTime =  $('#datetimepicker1').val();
		this.endTime =  $('#datetimepicker2').val();
		if(this.startTime==''||this.endTime==''){
			this.jsonApiService.message("起始结束时间不能为空");
			return;
		}
		let timeCheck=common.correctTimeParams(this.startTime,this.endTime,0);
		if(!timeCheck.status){
			this.jsonApiService.message(timeCheck.message);
			return;
		}
		var data = {
			parameters:{
				userName:this.userName,
				apiName:this.apiName,
				startTime:this.startTime,
				endTime:this.endTime,
				state:Number(this.timeType)
			}
		}
		if(!(this.apiName&&this.startTime&&this.endTime&&!this.userName)){
			this.isShow = true;
		}else{
			this.isShow = false;
		}
		let reqdata = 'gridPager='+JSON.stringify(data),url:string;
		url = "apistatistics/apiStatisticsListForpage.html";
		this.jsonApiService.http(url, reqdata).subscribe(data => {
			this.tableData = data.data;
			this.totalCount = data.data.length;
			this.client_pages(0,this.pageSize);
		})
	}
	//删除所选时间
	del_date(){
		this.startTime = '';
		this.endTime ='';
		$("#datetimepicker1").val('').change();
		$("#datetimepicker2").val('').change();
		$("#datetimepicker2").datetimepicker("setStartDate", null);
		$("#datetimepicker1").datetimepicker("setEndDate", null);
	}
	client_pages(start,length){
		this.resultTableData = this.tableData.slice(start,start+length);
	}
	//分页回调
	paginate(e){
		this.curPage = e.page+1;
		this.pageSize = e.rows;
		this.client_pages(e.first,e.rows);
	}
}